﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media;

namespace Microsoft.Windows.UserControls.Core.Extentions
{
    public static class DependencyObjectExtensions
    {
        public static DependencyObject GetParent(this DependencyObject element)
        {
            var parent = default(DependencyObject);
            try
            {
                parent = VisualTreeHelper.GetParent(element);
            }
            catch
            {
                parent = null;
            }

            if (parent == null)
            {
                var frameworkElement = element as FrameworkElement;
                if (frameworkElement != null)
                    parent = frameworkElement.Parent;
                
                var frameworkContentElement = element as FrameworkContentElement;
                if (frameworkContentElement != null)
                    parent = frameworkContentElement.Parent;
            }
            return parent;
        }

        public static IEnumerable<DependencyObject> GetParents(this DependencyObject element)
        {
            if (element == null)
                throw new ArgumentNullException("element");
        
            while (true)
            {
                var parent = element.GetParent();
                var dependencyObject = parent;
                element = parent;
                if (dependencyObject == null)
                    break;
                yield return element;
            }
        }

        public static T ParentOfType<T>(this DependencyObject element) where T : DependencyObject
        {
            if (element == null)
                return default(T);
            return element.GetParents().OfType<T>().FirstOrDefault<T>();
        }
    }
}